import settings from "@/config/settings";

/**
 * @description 添加单位
 * @param {String | Number} value 值 100
 * @param {String} unit 单位 px em rem
 */
export const addUnit = (value, unit = 'px') => {
	return !Object.is(Number(value), NaN) ? `${value}${unit}` : value
}

/**
 * @description 添加单位
 * @param {unknown} value
 * @return {Boolean}
 */
export const isEmpty = (value) => {
	return value == null && typeof value == 'undefined'
}

/**
 * @description 树转数组，队列实现广度优先遍历
 * @param {Array} data  数据
 * @param {Object} props `{ children: 'children' }`
 */

export const treeToArray = (data, props = {
	children: 'children'
}) => {
	data = cloneDeep(data)
	const {
		children
	} = props
	const newData = []
	const queue = []
	data.forEach((child) => queue.push(child))
	while (queue.length) {
		const item = queue.shift()
		if (item[children]) {
			item[children].forEach((child) => queue.push(child))
			delete item[children]
		}
		newData.push(item)
	}
	return newData
}

/**
 * @description 数组转
 * @param {Array} data  数据
 * @param {Object} props `{ parent: 'pid', children: 'children' }`
 */

export const arrayToTree = (
	data,
	props = {
		id: 'id',
		parentId: 'pid',
		children: 'children'
	}
) => {
	data = cloneDeep(data)
	const {
		id,
		parentId,
		children
	} = props
	const result = []
	const map = new Map()
	data.forEach((item) => {
		map.set(item[id], item)
		const parent = map.get(item[parentId])
		if (parent) {
			parent[children] = parent[children] ?? []
			parent[children].push(item)
		} else {
			result.push(item)
		}
	})
	return result
}

/**
 * @description 获取正确的路经
 * @param {String} path  数据
 */
export function getNormalPath(path) {
	if (path.length === 0 || !path || path == 'undefined') {
		return path
	}
	const newPath = path.replace('//', '/')
	const length = newPath.length
	if (newPath[length - 1] === '/') {
		return newPath.slice(0, length - 1)
	}
	return newPath
}

/**
 * @description对象格式化为Query语法
 * @param { Object } params
 * @return {string} Query语法
 */
export function objectToQuery(params) {
	let query = ''
	for (const props of Object.keys(params)) {
		const value = params[props]
		const part = encodeURIComponent(props) + '='
		if (!isEmpty(value)) {
			if (isObject(value)) {
				for (const key of Object.keys(value)) {
					if (!isEmpty(value[key])) {
						const params = props + '[' + key + ']'
						const subPart = encodeURIComponent(params) + '='
						query += subPart + encodeURIComponent(value[key]) + '&'
					}
				}
			} else {
				query += part + encodeURIComponent(value) + '&'
			}
		}
	}
	return query.slice(0, -1)
}

/**
 * @description 时间格式化
 * @param dateTime { number } 时间戳
 * @param fmt { string } 时间格式
 * @return { string }
 */
// yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合
export const timeFormat = (dateTime, fmt) => {
	// 如果为null,则格式化当前时间
	if (!dateTime) {
		dateTime = Number(new Date())
	}
	// 如果dateTime长度为10或者13，则为秒和毫秒的时间戳，如果超过13位，则为其他的时间格式
	if (dateTime.toString().length == 10) {
		dateTime *= 1000
	}
	const date = new Date(dateTime)
	let ret
	const opt = {
		'y+': date.getFullYear().toString(), // 年
		'm+': (date.getMonth() + 1).toString(), // 月
		'd+': date.getDate().toString(), // 日
		'h+': date.getHours().toString(), // 时
		'M+': date.getMinutes().toString(), // 分
		's+': date.getSeconds().toString() // 秒
	}
	for (const k in opt) {
		ret = new RegExp('(' + k + ')').exec(fmt)
		if (ret) {
			fmt = fmt.replace(
				ret[1],
				ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
			)
		}
	}
	return fmt
}

/**
 * @description 获取不重复的id
 * @param length { Number } id的长度
 * @return { String } id
 */
export const getNonDuplicateID = (length = 8) => {
	let idStr = Date.now().toString(36)
	idStr += Math.random().toString(36).substring(3, length)
	return idStr
}


/*
 * json数组去重
 * @param: {Array} jsonArr 去重之前的数组
 * @param  {String} field  需要去重的字段值
 */
export const deWeight = (jsonArr, field) => {
	// 数组长度小于2 或 没有指定去重字段 或 不是json格式数据
	if (jsonArr.length < 2 || !field || typeof jsonArr[0] !== "object") return jsonArr;
	let uniqueArr = [jsonArr[0]];
	field = field ? field : 'id';
	for (let i = 1; i < jsonArr.length; i++) {
		let item = jsonArr[i];
		let repeat = false; // 标识位
		for (let j = 0; j < uniqueArr.length; j++) {
			if (item[field] && item[field] == uniqueArr[j][field]) {
				repeat = true;
				break;
			}
		}
		if (!repeat) {
			uniqueArr.push(item);
		}
	}
	return uniqueArr;
}
export const dictByKeys = (dict, keys, keyname, keycode) => {
	keycode = keycode ? keycode : "value";
	keyname = keyname ? keyname : "label";
	let key = keys;
	if ((key == null || key == "" || key == undefined) && key != 0) {
		return '';
	}

	key = key != 0 ? String(key).split(',') : '0';
	let names = [];
	if (key.length != 0) {
		if (Array.isArray(dict)) {
			for (let i = 0; i < dict.length; i++) {
				for (let k = 0; k < key.length; k++) {
					if (dict[i][keycode] == key[k]) {
						names.push(dict[i][keyname]);
					}
				}
			}
		} else {
			for (let i in dict) {
				for (let k = 0; k < key.length; k++) {
					if (i == key[k]) {
						names.push(dict[i]);
					}
				}
			}

		}
		return names.join(',');
	} else if (key == 0) {
		for (let i in dict) {
			if (i == 0) {
				names.push(dict[i][keyname]);
			}
		}
		return names.join(',');
	} else {
		return '';
	}

}